from exceptiongroup import catch
from llama_index.core import SimpleDirectoryReader, VectorStoreIndex, StorageContext, Settings
from llama_index.core.node_parser import SimpleNodeParser
from llama_index.vector_stores.chroma import ChromaVectorStore
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
from llama_index.llms.huggingface import HuggingFaceLLM
import chromadb
import logging
logging.basicConfig(level=logging.DEBUG)

db = chromadb.PersistentClient(path="./chroma_db")

# 获取集合
chroma_collection = db.get_or_create_collection("quickstart")

print("使用本地知识库")

Settings.embed_model = HuggingFaceEmbedding(model_name=r"D:\self\python\AIModel\all-MiniLM-L6-v2", device="cpu")
llm = HuggingFaceLLM(model_name=r"D:\self\python\AIModel\Qwen2.5-0.5B-Instruct",
                     tokenizer_name=r"D:\self\python\AIModel\Qwen2.5-0.5B-Instruct",
                     model_kwargs={"trust_remote_code": True}, tokenizer_kwargs={"trust_remote_code": True})

# 设置全局llm属性，这样在所以查询时，会使用该模型
Settings.llm = llm

vector_size = Settings.embed_model._model.get_sentence_embedding_dimension()  # 获取实际维度

vector_store = ChromaVectorStore(chroma_collection=chroma_collection)
storage_content = StorageContext.from_defaults(vector_store=vector_store)

documents = SimpleDirectoryReader(r"data").load_data()

node_parser = SimpleNodeParser.from_defaults(chunk_size=512)
base_node = node_parser.get_nodes_from_documents(documents=documents)
index = VectorStoreIndex(nodes=base_node,show_progress=True)

# 讲索引持久化存储到本地向量数据库
index.storage_context.persist()

# index = VectorStoreIndex.from_documents(documents,storage_content=storage_content,embed_model=Settings.embed_model,show_progress=True)

query_engine = index.as_query_engine(similarity_top_k=3)
response = query_engine.query("数据分析工具链")
# query_chat = index.as_chat_engine()
# response = query_chat.chat("数据分析工具链")
print(response)

if __name__ == "__main__":
    print("test")
